/**
 * @description: pinia插件
 * @todo: 存储库刷新不丢失 + 标签页隔离
 * @example:
 *  independent: {
 *    enabled: true, // 是否开启隔离功能
 *    paths: ["data"], // 需要隔离的字段
 *  },
*/
export default ({ options, store }) => {
  const { independent } = options;
  if (independent?.enabled) {
    // 刷新完毕后: 将该本地存储数据赋值到库中, 并删除本地化
    independent.paths.forEach((key) => {
      const localKey = `${store.$id}-${key}`;
      const localData = localStorage.getItem(localKey);
      if (localData) {
        store[key] = localData;
        localStorage.removeItem(localKey);
      }
    });
    // 页面刷新前: 将该库数据存储到本地
    window.addEventListener("beforeunload", () => {
      independent.paths.forEach((key) => {
        const localKey = `${store.$id}-${key}`;
        const localData = store[key];
        localStorage.setItem(localKey, localData);
      });
    });
  }
};
